package com.szh.mysobproject.ui.activity.msg

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import com.dylanc.longan.lifecycleOwner
import com.szh.mysobproject.R
import com.szh.mysobproject.action.OnBack2TopListener
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.databinding.LikeMsgListActivityBinding
import com.szh.mysobproject.ui.adapter.AdapterDelegate
import com.szh.mysobproject.ui.adapter.LikeMsgAdapter
import com.szh.mysobproject.util.SimpleLinearSpaceItemDecoration
import com.szh.mysobproject.util.dp
import com.szh.mysobproject.util.loadStateListener
import com.szh.mysobproject.util.setDoubleClickListener
import com.szh.mysobproject.viewmodel.MsgViewModel
import com.szh.mysobproject.widget.StatusLayout
import kotlinx.coroutines.flow.collectLatest

/**
 * @author : create by  szh
 * @date : 2022/7/11 17:11
 * @desc :点赞消息列表
 */

class LikeMsgListActivity : AppActivity(), StatusAction, OnBack2TopListener {

    private val mBinding by viewBinding<LikeMsgListActivityBinding>()
    private val mMsgViewModel by viewModels<MsgViewModel>()
    private val mAdapterDelegate = AdapterDelegate()
    private val mLikeMsgAdapter = LikeMsgAdapter(mAdapterDelegate)
    private val loadStateListener = loadStateListener(mLikeMsgAdapter) {
        mBinding.refreshLayout.finishRefresh()
    }

    override fun getLayoutId(): Int = R.layout.like_msg_list_activity

    override fun initView() {
        mBinding.rvLikeMsgList.apply {
            adapter = mLikeMsgAdapter
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(SimpleLinearSpaceItemDecoration(4.dp))
        }
    }

    override fun initData() {
        lifecycleOwner.lifecycleScope.launchWhenCreated {
            mMsgViewModel.getLikeMsgList().collectLatest {
                mLikeMsgAdapter.submitData(it)
            }
        }
    }

    override fun initEvent() {
        titleBar?.setDoubleClickListener {
            onBack2Top()
        }
        mBinding.refreshLayout.setOnRefreshListener {
            mLikeMsgAdapter.refresh()
        }
        mLikeMsgAdapter.addLoadStateListener(loadStateListener)
        mAdapterDelegate.setOnItemClickListener { _, position -> }
    }

    override fun getStatusLayout(): StatusLayout = mBinding.hlLikeMsgHint

    override fun onBack2Top() {
        mBinding.rvLikeMsgList.smoothScrollToPosition(0)
    }

    override fun onDestroy() {
        super.onDestroy()
        mLikeMsgAdapter.removeLoadStateListener(loadStateListener)
    }
}